package com.hhkj.study.api.user.sevice.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.hhkj.study.admin.resource.model.res.ResourceQuestionBankRes;
import com.hhkj.study.admin.resource.service.biz.ResourceQuestionBankBizService;
import com.hhkj.study.admin.user.entity.User;
import com.hhkj.study.admin.user.model.podo.UserExerciseDo;
import com.hhkj.study.admin.user.model.podo.UserExercisePo;
import com.hhkj.study.admin.user.service.base.UserExerciseService;
import com.hhkj.study.admin.user.service.extend.UserExerciseExtendService;
import com.hhkj.study.admin.user.service.extend.UserExtendService;
import com.hhkj.study.api.user.common.checker.AccountChecker;
import com.hhkj.study.api.user.model.req.ApiCustomerUserCourseBaseReq;
import com.hhkj.study.api.user.model.req.ApiCustomerUserExerciseListRes;
import com.hhkj.study.api.user.model.req.ApiCustomerUserExerciseSaveReq;
import com.hhkj.study.api.user.model.req.ApiCustomerUserExerciseTrainReq;
import com.hhkj.study.api.user.model.res.ApiCustomerUserBaseRes;
import com.hhkj.study.api.user.sevice.biz.ApiCustomerUserExerciseBizService;
import com.hhkj.study.common.cache.GlobalCache;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.DictCodeEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.model.TrainLoginRes;
import com.ruoyi.common.model.dto.OutTrainLoginDTO;
import com.ruoyi.common.thirdparty.train.TrainApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author luowu
 * @Date 2024/9/27 涵 15:51:05
 */
@Slf4j
@Service
public class ApiCustomerUserExerciseBizServiceImpl implements ApiCustomerUserExerciseBizService {

    @Resource
    private UserExtendService userExtendService;

    @Resource
    private UserExerciseExtendService userExerciseExtendService;

    @Resource
    private UserExerciseService userExerciseService;

    @Resource
    private ResourceQuestionBankBizService questionBankBizService;

    @Resource
    private AccountChecker accountChecker;

    @Resource
    private TrainApiClient trainApiClient;

    @Resource
    private GlobalCache globalCache;

    /** 模拟练习类型 */
    private static final Integer MOCK_BANK_TYPE = 2;

    @Override
    public boolean save(ApiCustomerUserExerciseSaveReq req) {
        User customerUser = userExtendService.getByMobileOrIdCard(req.getMobile(), null);
        if (ObjectUtil.isNull(customerUser)) {
            log.error("用户不存在,手机号为{}", req.getMobile());
            return false;
        }
        req.setUserId(customerUser.getId());
        UserExerciseDo userExercise = BeanUtil.toBean(req, UserExerciseDo.class);
        userExercise.setQuestionCount(ObjectUtil.isEmpty(req.getCurrentTotalCount())
                ? req.getQuestionCount() : req.getCurrentTotalCount());
        return userExerciseExtendService.outsideSystemSave(userExercise);
    }

    @Override
    public List<ApiCustomerUserExerciseListRes> list(ApiCustomerUserCourseBaseReq req) {
        ApiCustomerUserBaseRes currentUser = accountChecker.checkAccountValid();
        // 练习记录中查询的是真题类型的记录
        Map<String, Long> bankTypeMap = globalCache.getIdByName(Lists.newArrayList(Constants.DEFAULT_TEST_BANK_TYPE
                        , Constants.EXERCISE_TEST_BANK_TYPE)
                , Lists.newArrayList(DictCodeEnum.BANK_TYPE.getCode()));
        if (ObjectUtil.isNull(bankTypeMap.get(Constants.DEFAULT_TEST_BANK_TYPE))
                || ObjectUtil.isNull(bankTypeMap.get(Constants.EXERCISE_TEST_BANK_TYPE))) {
            throw new GlobalException("题库字典类型缺失");
        }
        UserExerciseDo userExerciseDo = new UserExerciseDo();
        userExerciseDo.setUserId(currentUser.getId());
        userExerciseDo.setCourseId(req.getCourseId());
        userExerciseDo.setOrderItemId(req.getOrderItemId());
        userExerciseDo.setBankType(MOCK_BANK_TYPE.equals(req.getType())
                ? bankTypeMap.get(Constants.EXERCISE_TEST_BANK_TYPE) : bankTypeMap.get(Constants.DEFAULT_TEST_BANK_TYPE));
        List<UserExercisePo> userExerciseList = userExerciseService.listPoByDo(userExerciseDo);
        if (CollectionUtil.isEmpty(userExerciseList)) {
            return Lists.newArrayList();
        }
        return BeanUtil.copyToList(userExerciseList, ApiCustomerUserExerciseListRes.class);
    }

    @Override
    public String doExercise(ApiCustomerUserExerciseTrainReq req) {
        ApiCustomerUserBaseRes currentUser = accountChecker.checkAccountValid();
        ResourceQuestionBankRes questionBankRes = questionBankBizService.getById(req.getBankId());
        Long dictTypeId = globalCache.getIdBySimpleName(Constants.EXERCISE_TEST_BANK_TYPE, DictCodeEnum.BANK_TYPE.getCode());
        OutTrainLoginDTO trainLogin = new OutTrainLoginDTO();
        trainLogin.setMobile(currentUser.getMobile());
        trainLogin.setName(StrUtil.isBlank(currentUser.getName()) ? currentUser.getNickName() : currentUser.getName());
        trainLogin.setOutCourseId(questionBankRes.getAssoCourseId());
        trainLogin.setOutBankId(questionBankRes.getAssoBankId());
        TrainLoginRes trainLoginRes = trainApiClient.loginTrain(trainLogin);
        return StrUtil.format("{}?sk={}&id={}&outsideBankId={}&outsideBankType={}&outsideCourseId={}&outsideOrderItemId={}&mobile={}{}"
                , trainApiClient.getTrainTestAddressBySource(req.getSourceType())
                , trainLoginRes.getSessionKey(), questionBankRes.getAssoBankId(), req.getBankId()
                , questionBankRes.getType(), req.getCourseId(), req.getOrderItemId(), currentUser.getMobile()
                , ObjectUtil.equals(dictTypeId, questionBankRes.getType()) ? "&type=test" : "");
    }

}
